package com.macro.sms.service.impl;

import com.macro.sms.config.SmsTemplateCodeConfig;
import com.macro.sms.service.SmsService;
import com.macro.sms.utils.RandomUtil;
import com.macro.sms.utils.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ：小海
 * @dete ：2021-03-26 08:57:37
 * @Describe : 阿里云手机短信业务
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 获取手机验证码并放入redis中
     * @param phone
     * @return
     */
    @Override
    public int getPhoneCode(String phone) {

        //生成随机值，传递阿里云进行发送
        String code = RandomUtil.getFourBitRandom();

        //创建集合放入随机数
        Map<String, Object> param = new HashMap<>();
        param.put("code",code);
        //配置注册模板引擎
        boolean send = SmsUtil.send(phone,SmsTemplateCodeConfig.registerTemplate, param);
        //配置登录模板引擎
        //boolean send = SmsUtil.send(phone,SmsTemplateCodeConfig.loginTemplate, param);
        if (!send){
            return 0;
        }
        redisTemplate.opsForValue().set(phone,code,2L,TimeUnit.MINUTES);
        log.info("短信验证码为:"+code);
        return 1;
    }
}
